package org.example.studentmanager.service.impl;

import org.example.studentmanager.dao.StudentDao;
import org.example.studentmanager.dao.TeacherDao;
import org.example.studentmanager.dao.UserDao;
import org.example.studentmanager.entity.LoginInfo;
import org.example.studentmanager.entity.User;
import org.example.studentmanager.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private StudentDao studentDao;
    @Autowired
    private TeacherDao teacherDao;

    /**
     * 登录
     * @param user 用户的账号密码
     * @return 用户的登录信息
     * */
    @Override
    public LoginInfo login(User user) {
        User user1 = userDao.login(user.getUsername(), user.getPassword());
        if (user1 == null) {
            return null;
        }
        if (Objects.equals(user1.getRole(), "admin")) {
            return new LoginInfo(user1.getUsername(), user1.getPassword(), "admin", user1.getId());
        } else if (Objects.equals(user1.getRole(), "student")) {
            return new LoginInfo(user1.getUsername(), user1.getPassword(), user1.getRole(), user1.getId());
        } else {
            return new LoginInfo(user1.getUsername(), user1.getPassword(), user1.getRole(), user1.getId());
        }
    }

    @Override
    public boolean updatePassword(String username, String newPassword) {
        int id = userDao.getUserIdByUsername(username);
        int rows = userDao.updatePassword(id, newPassword);
        return rows > 0;
    }

    @Override
    public Integer getUserIdByUsername(String username) {
        return userDao.getUserIdByUsername(username);
    }
}
